home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14334 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  73 lines

  1. Path: ix.netcom.com!news
  2. From: jlilley@ix.netcom.com (John Lilley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Typecasting a class?  Help!
  5. Date: 29 Mar 1996 18:00:24 GMT
  6. Organization: Netcom
  7. Message-ID: <4jh8fo$1gp@dfw-ixnews6.ix.netcom.com>
  8. References: <dkelly.828048898@maestro.inav.net>
  9. NNTP-Posting-Host: den-co10-17.ix.netcom.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-NETCOM-Date: Fri Mar 29 12:00:24 PM CST 1996
  13. X-Newsreader: WinVN 0.99.7
  14.  
  15. In article <dkelly.828048898@maestro.inav.net>, dkelly@blue.weeg.uiowa.edu says...
  16. >
  17. >OK, we all know we can do this:
  18. >
  19. >x = 6;
  20. >printf("x is equal to %d\n",x);
  21. >
  22. >and it works fine.  But what I want to do is this:
  23. >
  24. >class MyInt
  25. >{
  26. >  public:
  27. >    int  iTheValue;
  28. >    operator int() { return iTheValue; };
  29. >    void SetValue(int iNewValue) { iTheValue = iNewValue; };
  30. >};
  31. >
  32. >MyInt clInteger;
  33. >clInteger.SetValue(6);
  34. >printf("clInteger is equal to %d\n", clInteger);
  35. >
  36. >
  37. >But it doesn't work unless I do this:
  38. >
  39. >printf("clInteger is equal to %d\n", (int)clInteger);
  40. >
  41. >Is there any way I can get an instance of MyInt to be seen as
  42. >and integer to printf without having to explicitly cast it as above?
  43.  
  44. No, since printf uses "..." for the final args, there is no way to
  45. make the implicit conversion to (int) happen.  
  46.  
  47.  
  48. However, since iostreams have an operator<< that takes an (int)
  49. as a argument, the implicit conversion to int will takes place
  50. for "cout << myInt".  IMHO, just one of the many advantages to 
  51. iostream vs stdio in the C++ context.
  52.  
  53. #include <iostream.h>
  54.  
  55. class MyInt
  56. {
  57.   public:
  58.     int  iTheValue;
  59.     operator int() { return iTheValue; };
  60.     void SetValue(int iNewValue) { iTheValue = iNewValue; };
  61. };
  62.  
  63. main()
  64. {
  65.    MyInt i;
  66.    i.iTheValue = 3;
  67.    cout << i << "\n";
  68.  
  69. }
  70.  
  71.  
  72.  
  73.